package cn.player.media.util;

import android.content.Context;
import android.util.SparseArray;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.player.R;
import cntv.player.core.util.StringUtil;
import cntv.player.core.util.Utils;
import cntv.player.engine.Const;
import cn.player.media.entity.PlayMode;

public class PlayModeUtil {


    /**
     * 组装不同码率播放地址
     *
     * @param hlsUrl    主地址
     * @param hlsSubUrl 不同码率地址
     * @return
     */
    public static String fitVodModeUrl(String hlsUrl, String hlsSubUrl) {
        if (hlsUrl == null || "".equals(hlsUrl.trim())) {
            return null;
        }

        if (!hlsUrl.startsWith("http://") && !hlsUrl.startsWith("https://")) {
            return null;
        }
        //    http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/6295d93f4e964903bc5bd89ab8d35b5f/main.m3u8
        String protocol = hlsUrl.substring(0, hlsUrl.indexOf(":"));//http
        String strtoken = hlsUrl.substring(hlsUrl.indexOf("/") + 2);
        int domainIdx = strtoken.indexOf("/");

        String domainName = "";
        if (domainIdx != -1) {
            domainName = strtoken.substring(0, domainIdx); //       asp.cntv.lxdns.com
        } else {
            return null;
        }

        String realUrl = null;
        if (hlsSubUrl.startsWith("http://") || hlsSubUrl.startsWith("https://")) {
            // contain whole real url
            realUrl = hlsSubUrl;
        } else if (hlsSubUrl.startsWith("/")) {
            // domain + subUrl;
            realUrl = protocol + "://" + domainName + hlsSubUrl;
        } else {
            // mainUrl + subUrl;
            realUrl = hlsUrl.substring(0, hlsUrl.lastIndexOf("/")) + "/" + hlsSubUrl;
        }
//		LogUtil.i("zl","realUrl = "  + realUrl);
        return realUrl;
    }

    /**
     * 获取点播码率列表
     *
     * @param context context
     * @param hlsUrl  hls地址
     * @param hlsInfo hls地址访问网络后获取到的码率源信息
     * @return
     */
    public static SparseArray<PlayMode> getVodPlayModeSparse(Context context, String hlsUrl, String hlsInfo) {
        SparseArray<PlayMode> mModeSparse = new SparseArray<PlayMode>();
        ByteArrayInputStream bais = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            bais = new ByteArrayInputStream(hlsInfo.getBytes());
            isr = new InputStreamReader(bais);
            br = new BufferedReader(isr);
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                if (line.contains("BANDWIDTH")) {
                    String bandWidth = line.split(",")[1].trim();//BANDWIDTH=204800
                    int width = Utils.strToInt(bandWidth.split("=")[1]);
                    if (width / 1000 > 1600) {
                        if (mModeSparse.indexOfKey(Const.PLAYER_MODE_PD) >= 0) { //超高清模式可能有很多，只要一个
                            continue;
                        }
                        //添加超高清模式
                        PlayMode modeUhd = new PlayMode();
                        modeUhd.setTitle(context.getString(R.string.player_mode_uhd));
                        modeUhd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeUhd.setRate(Const.PLAYER_MODE_UHD);
                        mModeSparse.put(Const.PLAYER_MODE_UHD, modeUhd);

                    } else if (width / 1000 > 900 && width / 1000 <= 1600) {

                        //添加超清模式
                        PlayMode modePd = new PlayMode();
                        modePd.setTitle(context.getString(R.string.player_mode_pd));
                        modePd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modePd.setRate(Const.PLAYER_MODE_PD);
//						mModeList.add(modePd); 
                        mModeSparse.put(Const.PLAYER_MODE_PD, modePd);
                    } else if (width / 1000 > 600 && width / 1000 <= 900) {
                        //添加高清模式
                        PlayMode modeHd = new PlayMode();
                        modeHd.setTitle(context.getString(R.string.player_mode_hd));
                        modeHd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeHd.setRate(Const.PLAYER_MODE_HD);
                        mModeSparse.put(Const.PLAYER_MODE_HD, modeHd);
                    } else if (width / 1000 > 300 && width / 1000 <= 600) {
                        //添加标清模式
                        PlayMode modeSd = new PlayMode();
                        modeSd.setTitle(context.getString(R.string.player_mode_sd));
                        modeSd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeSd.setRate(Const.PLAYER_MODE_SD);
                        mModeSparse.put(Const.PLAYER_MODE_SD, modeSd);
                    } else if (width / 1000 <= 300) {
                        //添加极速模式
                        PlayMode modeTs = new PlayMode();
                        modeTs.setTitle(context.getString(R.string.player_mode_ts));
                        modeTs.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeTs.setRate(Const.PLAYER_MODE_TS);
                        mModeSparse.put(Const.PLAYER_MODE_TS, modeTs);
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                    br = null;
                }
                if (isr != null) {
                    isr.close();
                    isr = null;
                }
                if (bais != null) {
                    bais.close();
                    bais = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return mModeSparse;

    }

    /**
     * 根据每个码率地址获取ts文件地址列表
     *
     * @param m3u8Url     传入的码率地址
     * @param m3u8UrlInfo 码率地址访问网络后获取到的ts文件信息
     * @return
     */
    public static List<String> getM3U8VideoUrlList(String m3u8Url, String m3u8UrlInfo) {
        String playUrl = m3u8Url.substring(0, m3u8Url.lastIndexOf("/") + 1);
        List<String> m3u8UrlList = new ArrayList<String>();

        ByteArrayInputStream bais = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            bais = new ByteArrayInputStream(m3u8UrlInfo.getBytes());
            isr = new InputStreamReader(bais);
            br = new BufferedReader(isr);
            for (String line = br.readLine(); line != null; line = br.readLine()) {
//				if(line.endsWith(".ts")){
                if (line.contains(".ts")) {
                    m3u8UrlList.add(playUrl + line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                    br = null;
                }
                if (isr != null) {
                    isr.close();
                    isr = null;
                }
                if (bais != null) {
                    bais.close();
                    bais = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return m3u8UrlList;
    }


    /**
     * 将SparseArray列表数据转换为List数据
     *
     * @param sparePlayMode
     * @return
     */
    public static List<PlayMode> copyToList(SparseArray<PlayMode> sparePlayMode) {
        ArrayList<PlayMode> modeList = new ArrayList<PlayMode>();
        for (int i = 0; i < sparePlayMode.size(); i++) {
            modeList.add(sparePlayMode.valueAt(i));
        }
        return modeList;
    }


    /**
     * 将码率列表按码率值降序排列
     *
     * @param modes
     */
    public static void sortModeList(List<PlayMode> modes) {
        if (modes != null && modes.size() > 0) {
            Collections.sort(modes, new Comparator<PlayMode>() {

                @Override
                public int compare(PlayMode lhs, PlayMode rhs) {

                    // TODO Auto-generated method stub
                    if (lhs.getRate() > rhs.getRate()) {
                        return 1;
                    } else if (lhs.getRate() < rhs.getRate()) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
        }
    }

}
